package top.jacktgq.itheima.bio.TCP.Demo2;

import java.io.*;
import java.net.Socket;
import java.util.Random;

public class Upload implements Runnable{

	private Socket socket;
	
	public Upload(Socket socket){
		this.socket = socket;
	}

	@Override
	public void run() {

        try {
			//通过客户端连接对象，获取字节输入流，读取客户端图片
			InputStream in = socket.getInputStream();
			
			//防止文件被覆盖，从新定义文件名字
			//规则：域名+毫秒值+6位随机数字
			String fileName = "JackTGQ" + System.currentTimeMillis() 
			                            + new Random().nextInt(999999) 
			                            + ".png";
			//创建File目的文件
			File f = new File("images/TCPServer/" + fileName);
			
			//创建字节输出流，将图片写入到目的文件中
			FileOutputStream fos = new FileOutputStream(f);
			
			//读写字节数组
			int len = 0;
			byte[] bytes = new byte[1024];
			while((len = in.read(bytes))!=-1){
				fos.write(bytes,0,len);
			}
			
			OutputStream out = socket.getOutputStream();
			out.write("上传成功！".getBytes());
			
			fos.close();
			socket.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
